package net.posick.ws;

import net.posick.ws.soap.ISOAPServerService;
import net.posick.ws.soap.SOAPServerService;
import net.posick.ws.xml.Name;
import net.posick.ws.xml.Namespace;
import net.posick.ws.xml.XmlElement;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity
{
    protected static final String LOG_TAG = MainActivity.class.getName();
    
    
    protected class EndpointBroadcastReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if (intent != null)
            {
                String action = intent.getAction();
                
                XmlElement response = null;
                
                Bundle bundle = getResultExtras(true);
                setResultExtras(bundle);
                try
                {
                    if ("http://example.com/someRequest".equals(action))
                    {
                        bundle.putString(net.posick.ws.Constants.EXTRA_SOAP_ACTION_RESPONSE, "http://example.com/someResponse");
                        response = new XmlElement(new Name(new Namespace("hello", "http://example.com/example"), "someResponse")).setValue("Hello World");
                    }
                    if (response != null)
                    {
                        setResultCode(Activity.RESULT_OK);
                        setResultData(response.toString());
                        bundle.putSerializable(net.posick.ws.Constants.EXTRA_RESPONSE, response);
                    }
                } catch (Exception e)
                {
                    bundle.putSerializable(net.posick.ws.Constants.EXTRA_SOAP_FAULT, e);
                }
            }
        }
    }
    
    private ServiceConnection soapServiceConnection = new ServiceConnection()
    {
        @Override
        public void onServiceConnected(ComponentName className, IBinder binder)
        {
            soapService = ISOAPServerService.Stub.asInterface(binder);
            try
            {
                IntentFilter filter = new IntentFilter();
                try
                {
                    filter.addDataType(net.posick.ws.Constants.MEDIA_TYPE_SOAP);
                    filter.addCategory(net.posick.ws.Constants.CATEGORY_ENDPOINT_CALLBACK);
                    filter.addAction("http://example.com/someRequest");
                    filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
                    registerReceiver(new EndpointBroadcastReceiver(), filter, Constants.PERMISSION_REGISTER_ENDPOINT, null);
                    soapService.register("/example", "http://example.com/someRequest", new Intent("http://example.com/someRequest"));
                } catch (MalformedMimeTypeException e)
                {
                }
            } catch (RemoteException e)
            {
            }
        }
        
        
        @Override
        public void onServiceDisconnected(ComponentName className)
        {
            try
            {
                soapService.unregister("/example", "http://example.com/someRequest");
            } catch (RemoteException e)
            {
            }
            soapService = null;
        }
    };
    
    protected ISOAPServerService soapService;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        try
        {
            Intent startIntent = new Intent(createPackageContext("net.posick.ws", 0), SOAPServerService.class);
            startService(startIntent);
            if (!bindService(startIntent, soapServiceConnection, Context.BIND_IMPORTANT | Context.BIND_ABOVE_CLIENT))
            {
                Log.e(LOG_TAG, "-----> Could NOT bind to SOAP service using action \"" + SOAPServerService.class.getName() + "\" and Package \"net.posick.ws\" <-----");
                try
                {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=net.posick.ws"));
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                    startActivity(intent);
                } catch (android.content.ActivityNotFoundException anfe)
                {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=net.posick.ws")));
                }
                return;
            }
        } catch (Exception e)
        {
            Log.e(LOG_TAG, e.getMessage(), e);
            Toast toast = Toast.makeText(null, "Could NOT bind to service \"" + SOAPServerService.class.getName() + "\".\n" + e.getLocalizedMessage(), Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}
